# ==========================================================
# Functional Pathway Clustering Script
# ----------------------------------------------------------
# Input : g:Profiler GO:BP enrichment result (Excel, one sheet)
# Output: (i) cluster-level summary per condition
#         (ii) pathway-level details with cluster assignment
# Clustering:
#   - similarity: Jaccard coefficient (gene overlap)
#   - distance  : 1 - Jaccard
#   - linkage   : average
#   - cut height: h = 0.5 (min. Jaccard similarity 0.5 within clusters)
# ==========================================================

## ---- User parameters -------------------------------------

# Path to g:Profiler Excel file
go_bp_file <- "PATH/TO/gProfiler_results.xlsx"

# Sheet name containing GO:BP results for one condition
sheet_name <- "GO BP"

# Output directory and file name
output_dir  <- "PATH/TO/output_directory"
output_file <- "Clustering_GO_BP_min_padj.xlsx"

# Height at which to cut the dendrogram (Jaccard distance)
cut_height <- 0.5

## ---- Packages --------------------------------------------

required_packages <- c("tidyverse", "openxlsx", "stringr")
for (pkg in required_packages) {
  if (!requireNamespace(pkg, quietly = TRUE)) {
    install.packages(pkg)
  }
  library(pkg, character.only = TRUE)
}

dir.create(output_dir, showWarnings = FALSE, recursive = TRUE)

## ---- Jaccard distance function ---------------------------

# list1, list2: lists of character vectors (gene sets)
jaccard_dist <- function(list1, list2) {
  sapply(list1, function(x)
    sapply(list2, function(y) {
      x <- trimws(x); y <- trimws(y)
      inter <- length(intersect(x, y))
      union <- length(unique(c(x, y)))
      if (union == 0) return(0)
      1 - inter / union
    })
  )
}

message("\nProcessing sheet: ", sheet_name)

## ---- Read data -------------------------------------------

dat <- openxlsx::read.xlsx(go_bp_file, sheet = sheet_name)

# Expected g:Profiler-like columns:
#   intersections      : comma-separated genes
#   term_id, term_name : GO ID and term name
#   intersection_size  : number of genes in the overlap
#   adjusted_p_value   : adjusted enrichment score
req_cols <- c(
  "intersections",
  "term_id",
  "term_name",
  "intersection_size",
  "adjusted_p_value"
)

missing <- setdiff(req_cols, names(dat))
if (length(missing) > 0) {
  stop("Missing required columns in sheet '", sheet_name, "': ",
       paste(missing, collapse = ", "))
}

dat$GeneList     <- stringr::str_split(dat$intersections, ",\\s*")
dat$Pathway_Name <- paste(dat$term_id, dat$term_name, sep = ": ")

results_list <- list()

## ---- Handle 0 or 1 pathway -------------------------------

if (nrow(dat) == 0) {

  message("No pathways in '", sheet_name, "' - nothing to cluster.")

} else if (nrow(dat) < 2) {

  message("Less than 2 pathways in '", sheet_name,
          "' - clustering skipped, all assigned to Cluster 1.")
  dat$Cluster <- 1

  cluster_summaries <- dat %>%
    dplyr::group_by(Cluster) %>%
    dplyr::summarise(
      pathways        = paste(Pathway_Name, collapse = " | "),
      n_pathways      = dplyr::n(),
      n_genes         = length(unique(unlist(GeneList))),
      genes           = paste(sort(unique(unlist(GeneList))), collapse = ", "),
      overlap_genes   = paste(
        tryCatch(Reduce(intersect, GeneList),
                 error = function(e) character()),
        collapse = ", "
      ),
      n_overlap_genes = length(
        tryCatch(Reduce(intersect, GeneList),
                 error = function(e) character())
      ),
      padj_min        = min(adjusted_p_value, na.rm = TRUE),
      pathway_padj_min = term_name[which.min(adjusted_p_value)]
    ) %>%
    dplyr::ungroup()

  pathway_details <- dat %>%
    dplyr::select(
      Cluster,
      Pathway_Name,
      intersection_size,
      intersections,
      adjusted_p_value
    ) %>%
    dplyr::arrange(Cluster)

  results_list[["Cluster_Summary"]]  <- cluster_summaries
  results_list[["Pathway_Details"]]  <- pathway_details

} else {

  ## ---- Jaccard distance + hierarchical clustering -------

  jacmat <- jaccard_dist(dat$GeneList, dat$GeneList)
  rownames(jacmat) <- dat$Pathway_Name
  colnames(jacmat) <- dat$Pathway_Name

  hc <- hclust(as.dist(jacmat), method = "average")
  dat$Cluster <- cutree(hc, h = cut_height)

  ## ---- Summaries per cluster -----------------------------

  cluster_summaries <- dat %>%
    dplyr::group_by(Cluster) %>%
    dplyr::summarise(
      pathways        = paste(Pathway_Name, collapse = " | "),
      n_pathways      = dplyr::n(),
      n_genes         = length(unique(unlist(GeneList))),
      genes           = paste(sort(unique(unlist(GeneList))), collapse = ", "),
      overlap_genes   = paste(
        tryCatch(Reduce(intersect, GeneList),
                 error = function(e) character()),
        collapse = ", "
      ),
      n_overlap_genes = length(
        tryCatch(Reduce(intersect, GeneList),
                 error = function(e) character())
      ),
      padj_min        = min(adjusted_p_value, na.rm = TRUE),
      pathway_padj_min = term_name[which.min(adjusted_p_value)]
    ) %>%
    dplyr::ungroup()

  pathway_details <- dat %>%
    dplyr::select(
      Cluster,
      Pathway_Name,
      intersection_size,
      intersections,
      adjusted_p_value
    ) %>%
    dplyr::arrange(Cluster)

  results_list[["Cluster_Summary"]] <- cluster_summaries
  results_list[["Pathway_Details"]] <- pathway_details
}

## ---- Write output ----------------------------------------

if (length(results_list) > 0) {
  out_path <- file.path(output_dir, output_file)
  openxlsx::write.xlsx(results_list, file = out_path)
  message("\nClustering complete. Results written to:\n", out_path, "\n")
} else {
  message("\nNo results to write.\n")
}

## ---- Plotting cluster summaries across multiple conditions ----

# ==========================================================
# Cluster visualization script (run AFTER clustering script)
# ----------------------------------------------------------
# Input : Excel file with Cluster_Summary sheets for multiple conditions
# Output: Two bubble plots as TIFF + PDF:
#   (1) Overlapping clusters (present in ≥2 conditions)
#   (2) Unique clusters (present in exactly 1 condition)
# ==========================================================

## ---- User parameters -------------------------------------

# Path to Excel file with Cluster_Summary sheets
cluster_file <- "PATH/TO/clustering_results.xlsx"

# Sheet names (one per condition) and corresponding condition labels
# Example format: c("SH_up_Cluster_Summary", "55_up_Cluster_Summary", ...)
sheet_vec <- c(
  "SH_up_Cluster_Summary",
  "55_up_Cluster_Summary", 
  "58_up_Cluster_Summary",
  "64_up_Cluster_Summary"
)

# Condition names (same order as sheet_vec)
cond_names <- c("SH1000", "EDCC 5055", "EDCC 5458", "EDCC 5464")
names(cond_names) <- sheet_vec

# Output directory
output_dir <- "PATH/TO/output_plots"

## ---- Packages --------------------------------------------

library(readxl)
library(ggplot2)
library(viridis)
library(dplyr)
library(purrr)
library(grid) # provides unit()

dir.create(output_dir, showWarnings = FALSE, recursive = TRUE)

## ---- Read and combine all sheets -------------------------

all_df <- map_dfr(sheet_vec, function(sh) {
  df <- readxl::read_excel(cluster_file, sheet = sh)
  df$condition <- cond_names[[sh]]
  df
})

## ---- Data preparation ------------------------------------

all_df <- all_df %>%
  mutate(
    condition     = factor(condition, levels = cond_names),
    padj_numeric  = as.numeric(padj_min),
    padj_numeric  = if_else(is.na(padj_numeric), 1e-10, padj_numeric),
    padj_log      = -log10(padj_numeric),
    `Cluster Name` = enc2utf8(`Cluster Name`)  # handle special characters
  )

## ---- Plot 1: Overlapping clusters (≥2 conditions) --------

# Clusters present in at least 2 conditions
clusters_multi <- all_df %>%
  distinct(condition, `Cluster Name`) %>%
  count(`Cluster Name`) %>%
  filter(n >= 2) %>%
  pull(`Cluster Name`)

plot_df <- all_df %>%
  filter(`Cluster Name` %in% clusters_multi) %>%
  group_by(`Cluster Name`) %>%
  mutate(mean_padj = mean(padj_numeric, na.rm = TRUE)) %>%
  ungroup() %>%
  mutate(`Cluster Name` = factor(`Cluster Name`,
                                 levels = unique(`Cluster Name`[order(mean_padj)])))

p_overlap <- ggplot(plot_df,
                    aes(x = condition, y = `Cluster Name`,
                        fill = padj_log, size = n_genes)) +
  geom_point(shape = 21, color = "black") +
  scale_fill_viridis(
    option = "magma",
    name = "-log10(min padj)",
    guide = guide_colorbar(
      title.position = "top",
      title.hjust    = 0.5,
      barwidth       = 15,
      barheight      = 1,
      title.theme    = element_text(size = 14),
      label.theme    = element_text(size = 12)
    )
  ) +
  scale_size_continuous(
    range = c(2, 12),
    name = "number of genes",
    guide = guide_legend(
      title.position = "top",
      title.hjust    = 0.5,
      title.theme    = element_text(size = 14),
      override.aes   = list(shape = 21, fill = "gray50"),
      keywidth       = unit(1.5, "cm"),
      keyheight      = unit(1.5, "cm")
    )
  ) +
  guides(size = guide_legend(order = 1),
         fill = guide_colorbar(order = 2)) +
  theme_minimal() +
  theme(
    axis.title.x  = element_blank(),
    axis.title.y  = element_blank(),
    axis.text.y   = element_text(size = 8),
    strip.text.x  = element_text(size = 10, face = "bold"),
    legend.position = "right",
    legend.direction = "vertical",
    legend.box       = "vertical",
    legend.box.just  = "center",
    legend.title.align = 0.5,
    legend.text.align  = 0.5,
    legend.key.width   = unit(1.5, "cm"),
    legend.key.height  = unit(1.5, "cm")
  )

ggsave(file.path(output_dir, "ggplot_cluster_padj_up_4conditions_overlap_ordered.tif"),
       plot = p_overlap, width = 10, height = 10, units = "in", dpi = 300)
ggsave(file.path(output_dir, "ggplot_cluster_padj_up_4conditions_overlap_ordered.pdf"),
       plot = p_overlap, width = 10, height = 10, units = "in")

## ---- Plot 2: Unique clusters (exactly 1 condition) -------

clusters_unique <- all_df %>%
  distinct(condition, `Cluster Name`) %>%
  count(`Cluster Name`) %>%
  filter(n == 1) %>%
  pull(`Cluster Name`)

unique_df <- all_df %>%
  filter(`Cluster Name` %in% clusters_unique)

# Order clusters blockwise by condition (fixed sequence for four conditions)
order_by_condition <- function(cond) {
  unique_df %>%
    filter(condition == cond) %>%
    distinct(`Cluster Name`) %>%
    pull(`Cluster Name`)
}

order_vec <- c(
  order_by_condition(cond_names[1]),
  order_by_condition(cond_names[2]),
  order_by_condition(cond_names[3]),
  order_by_condition(cond_names[4])
)

unique_df <- unique_df %>%
  mutate(`Cluster Name` = factor(`Cluster Name`, levels = order_vec))

p_unique <- ggplot(unique_df,
                   aes(x = condition, y = `Cluster Name`,
                       fill = padj_log, size = n_genes)) +
  geom_point(shape = 21, color = "black") +
  scale_fill_viridis(
    option = "magma",
    name = "-log10(min padj)",
    guide = guide_colorbar(
      title.position = "top",
      title.hjust    = 0.5,
      barwidth       = 15,
      barheight      = 1,
      title.theme    = element_text(size = 14),
      label.theme    = element_text(size = 12)
    )
  ) +
  scale_size_continuous(
    range = c(2, 12),
    name = "number of genes",
    guide = guide_legend(
      title.position = "top",
      title.hjust    = 0.5,
      title.theme    = element_text(size = 14),
      override.aes   = list(shape = 21, fill = "gray50"),
      keywidth       = unit(1.5, "cm"),
      keyheight      = unit(1.5, "cm")
    )
  ) +
  guides(size = guide_legend(order = 1),
         fill = guide_colorbar(order = 2)) +
  facet_grid(. ~ condition, scales = "free_y", space = "free_y") +
  theme_minimal() +
  theme(
    axis.title.x  = element_blank(),
    axis.title.y  = element_blank(),
    axis.text.y   = element_text(size = 8),
    strip.text.x  = element_text(size = 10, face = "bold"),
    strip.placement = "outside",
    strip.background = element_rect(fill = NA, colour = "black"),
    legend.position = "right",
    legend.direction = "vertical",
    legend.box       = "vertical",
    legend.box.just  = "center",
    legend.title.align = 0.5,
    legend.text.align  = 0.5,
    legend.key.width   = unit(1.5, "cm"),
    legend.key.height  = unit(1.5, "cm")
  )

ggsave(file.path(output_dir, "ggplot_cluster_padj_up_4conditions_unique_ordered.tif"),
       plot = p_unique, width = 8, height = 10, units = "in", dpi = 300)
ggsave(file.path(output_dir, "ggplot_cluster_padj_up_4conditions_unique_ordered.pdf"),
       plot = p_unique, width = 8, height = 10, units = "in")

message("\nPlots saved to: ", output_dir, "\n")

